package com.cyt.web.controller.reward.phone;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import com.cyt.base.model.dto.ReturnResult;
import com.cyt.base.util.BaseUtil;
import com.cyt.base.util.ErrorCode;
import com.cyt.base.util.ProProperties;
import com.cyt.reward.model.po.RewardShop;
import com.cyt.reward.model.po.RewardStaff;
import com.cyt.reward.model.vo.*;
import com.cyt.reward.service.*;
import com.cyt.reward.util.RewardDictCode;
import com.cyt.sys.util.FilePathUtil;
import com.cyt.web.controller.base.PhoneController;
import com.cyt.wx.model.po.WxMember;
import com.cyt.wx.service.WxMemberService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.Date;
import java.util.List;

/**
 * @author rong yuan
 * @date 2019/7/25 09:10
 */
@RestController
public class PhoneRewardController extends PhoneController {

    @Resource
    private WxMemberService wxMemberService;
    @Resource
    private RewardStaffService rewardStaffService;
    @Resource
    private RewardMoneyService rewardMoneyService;
    @Resource
    private RewardRecordService rewardRecordService;
    @Resource
    private RewardTagService rewardTagService;
    @Resource
    private RewardShopService rewardShopService;
    @Resource
    private RewardCashOutService rewardCashOutService;

    private RewardStaff acceptToken(WxMember wxMember) {
        if (wxMember != null) {
            RewardStaffVo rewardStaffVo = new RewardStaffVo();
            rewardStaffVo.setApplyId(wxMember.getApplyId());
            rewardStaffVo.setMemberId(wxMember.getId());
            RewardStaff rewardStaff = rewardStaffService.selectOneByCondition(rewardStaffVo);
            if (rewardStaff != null) {
                return rewardStaff;
            }
        }
        return null;
    }

    private WxMember acceptStaffId(String staffId) {
        RewardStaff rewardStaff = rewardStaffService.selectByPrimaryKey(staffId);
        if (rewardStaff != null) {
            WxMember wxMember = wxMemberService.selectByPrimaryKey(rewardStaff.getMemberId());
            if (wxMember != null) {
                return wxMember;
            }
        }
        return null;
    }

    /**
     * 跳转打赏界面
     *
     * @param token   用户信息
     * @param applyId 应用ID
     * @param staffId 员工ID
     * @return ModelAndView
     * @author rong yuan
     * @date 2019/7/9 09:08
     */
    @RequestMapping(value = "/phone/reward/rewardIndex", method = RequestMethod.GET)
    public ModelAndView rewardIndex(String token, String applyId, String staffId) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("/mobile/reward/rewardIndex");
        modelAndView.addObject("wxMember", acceptToken(token));
        modelAndView.addObject("token", token);
        modelAndView.addObject("applyId", applyId);
        modelAndView.addObject("staffId", staffId);

        RewardStaff rewardStaff = rewardStaffService.selectByPrimaryKey(staffId);
        if (rewardStaff != null) {
            WxMember wxMember = wxMemberService.selectByPrimaryKey(rewardStaff.getMemberId());
            if (wxMember != null) {
                modelAndView.addObject("headLogo", wxMember.getHeadLogo());
            } else {
                modelAndView.addObject("headLogo", "");
            }
            modelAndView.addObject("name", rewardStaff.getName());
            modelAndView.addObject("jobNum", rewardStaff.getJobNum());
        } else {
            modelAndView.addObject("headLogo", "");
            modelAndView.addObject("name", "");
            modelAndView.addObject("jobNum", "");
        }
        RewardMoneyVo rewardMoneyVo = new RewardMoneyVo();
        rewardMoneyVo.setApplyId(applyId);
        modelAndView.addObject(rewardMoneyService.list(rewardMoneyVo));
        RewardTagVo rewardTagVo = new RewardTagVo();
        rewardTagVo.setApplyId(applyId);
        modelAndView.addObject(rewardTagService.list(rewardTagVo));
        return modelAndView;
    }

    /**
     * 保存打赏记录
     *
     * @param token          用户信息
     * @param rewardRecordVo 接受参数对象
     * @return ReturnResult
     * @author rong yuan
     * @date 2019-7-24 11:19:40
     */
    @RequestMapping(value = "/phone/rewardrecord/addOrUpdate", method = RequestMethod.POST)
    public ReturnResult addOrUpdate(String token, RewardRecordVo rewardRecordVo) {
        rewardRecordVo.setMemberId(acceptToken(token).getId());
        if (StrUtil.isNotEmpty(rewardRecordVo.getMoney()) && Double.parseDouble(rewardRecordVo.getMoney()) > 0) {
            rewardRecordVo.setPayStatus(RewardDictCode.REWARD_PAY_STATUS_DZF);
        } else {
            rewardRecordVo.setPayStatus(RewardDictCode.REWARD_PAY_STATUS_YZF);
        }
        return rewardRecordService.addOrUpdate(rewardRecordVo, null);
    }

    /**
     * 跳转个人界面
     *
     * @param token   用户信息
     * @param applyId 应用ID
     * @return ModelAndView
     * @author rong yuan
     * @date 2019/7/9 09:08
     */
    @RequestMapping(value = "/phone/reward/personalIndex", method = RequestMethod.GET)
    public ModelAndView personalIndex(String token, String applyId) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("/mobile/reward/personalIndex");
        modelAndView.addObject("token", token);
        modelAndView.addObject("applyId", applyId);

        WxMember wxMember = acceptToken(token);
        modelAndView.addObject("headLogo", wxMember.getHeadLogo());

        RewardStaff rewardStaff = acceptToken(wxMember);
        if (rewardStaff != null) {
            modelAndView.addObject("name", rewardStaff.getName());
            modelAndView.addObject("jobNum", rewardStaff.getJobNum());
            modelAndView.addObject("stars", String.valueOf(rewardStaff.getStars()));
            if (StringUtils.isBlank(rewardStaff.getMemberId())) {
                modelAndView.addObject("verified", false);
            } else {
                modelAndView.addObject("verified", true);
            }
        } else {
            modelAndView.addObject("name", BaseUtil.decodeBase64(wxMember.getNickName()));
            modelAndView.addObject("jobNum", "");
            modelAndView.addObject("stars", "5");
            modelAndView.addObject("verified", false);
        }
        return modelAndView;
    }

    /**
     * 跳转我的二维码界面
     *
     * @param token   用户信息
     * @param applyId 应用ID
     * @return ModelAndView
     * @author rong yuan
     * @date 2019/7/9 09:08
     */
    @RequestMapping(value = "/phone/reward/myQrCode", method = RequestMethod.GET)
    public ModelAndView myQrCode(HttpServletRequest request, String token, String applyId) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("/mobile/reward/myQrCode");
        modelAndView.addObject("token", token);
        modelAndView.addObject("applyId", applyId);

        WxMember wxMember = acceptToken(token);
        modelAndView.addObject("headLogo", wxMember.getHeadLogo());
        RewardStaff rewardStaff = acceptToken(wxMember);
        if (rewardStaff != null) {
            modelAndView.addObject("name", rewardStaff.getName());

            //生成二维码
            String realPath = FilePathUtil.acceptCheckRealPath(request);
            File file;
            String directory = "/qrcode/";
            file = FileUtil.file(realPath + directory);
            if (!file.exists()) {
                file.mkdirs();
            }

            String filePath = directory + rewardStaff.getId() + ".jpg";
            file = FileUtil.file(realPath + "/" + filePath);
            String content = ProProperties.getInstance().getBaseUrl() + "/weChat/oauth?applyId=" + applyId + "&path=/phone/reward/rewardIndex&pathParams=staffId*" + rewardStaff.getId();
            QrCodeUtil.generate(content, 270, 270, file);
            modelAndView.addObject("qrCode", "/sysFile/showFileByPath?path=" + filePath);
        } else {
            modelAndView.addObject("name", BaseUtil.decodeBase64(wxMember.getNickName()));
            modelAndView.addObject("qrCode", "");
        }
        return modelAndView;
    }

    /**
     * 跳转我的赏金界面
     *
     * @param token   用户信息
     * @param applyId 应用ID
     * @return ModelAndView
     * @author rong yuan
     * @date 2019/7/9 09:08
     */
    @RequestMapping(value = "/phone/reward/myReward", method = RequestMethod.GET)
    public ModelAndView myReward(String token, String applyId) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("/mobile/reward/myReward");
        modelAndView.addObject("token", token);
        modelAndView.addObject("applyId", applyId);

        WxMember wxMember = acceptToken(token);
        modelAndView.addObject("headLogo", wxMember.getHeadLogo());
        RewardStaff rewardStaff = acceptToken(wxMember);
        if (rewardStaff != null) {
            modelAndView.addObject("haveMoney", rewardStaff.getHaveMoney());
            modelAndView.addObject("totalMoney", rewardStaff.getTotalMoney());
            modelAndView.addObject("cashOutMoney", rewardStaff.getTotalMoney() - rewardStaff.getHaveMoney());
            RewardRecordVo rewardRecordVo = new RewardRecordVo();
            rewardRecordVo.setApplyId(applyId);
            rewardRecordVo.setStaffId(rewardStaff.getId());
            rewardRecordVo.setStartTime(DateUtil.beginOfDay(DateUtil.yesterday().toJdkDate()).toString(DatePattern.NORM_DATETIME_PATTERN));
            rewardRecordVo.setEndTime(DateUtil.endOfDay(DateUtil.yesterday().toJdkDate()).toString(DatePattern.NORM_DATETIME_PATTERN));
            rewardRecordVo.setPayStatus(RewardDictCode.REWARD_PAY_STATUS_YZF);
            modelAndView.addObject("latestMoney", rewardRecordService.statisticsMoney(rewardRecordVo));
        } else {
            modelAndView.addObject("haveMoney", 0);
            modelAndView.addObject("totalMoney", 0);
            modelAndView.addObject("cashOutMoney", 0);
            modelAndView.addObject("latestMoney", 0);
        }

        return modelAndView;
    }

    /**
     * 跳转提现界面
     *
     * @param token   用户信息
     * @param applyId 应用ID
     * @return ModelAndView
     * @author rong yuan
     * @date 2019/7/9 09:08
     */
    @RequestMapping(value = "/phone/reward/myCashOut", method = RequestMethod.GET)
    public ModelAndView myCashOut(String token, String applyId) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("/mobile/reward/myCashOut");
        modelAndView.addObject("token", token);
        modelAndView.addObject("applyId", applyId);

        RewardStaff rewardStaff = acceptToken(acceptToken(token));
        if (rewardStaff != null) {
            modelAndView.addObject("haveMoney", rewardStaff.getHaveMoney());
            modelAndView.addObject("account", rewardStaff.getAccount());
        } else {
            modelAndView.addObject("haveMoney", 0);
            modelAndView.addObject("account", "");
            modelAndView.addObject("limitDescription", "");
        }

        RewardShopVo rewardShopVo = new RewardShopVo();
        rewardShopVo.setApplyId(applyId);
        List<RewardShop> rewardShopList = rewardShopService.list(rewardShopVo);
        if (rewardShopList != null && rewardShopList.size() == 1) {
            modelAndView.addObject("limitDescription", rewardShopList.get(0).getLimitDescription());
        } else {
            modelAndView.addObject("limitDescription", "");
        }
        return modelAndView;
    }

    /**
     * 保存提现明细
     *
     * @param token           用户信息
     * @param rewardCashOutVo 接受参数对象
     * @return ReturnResult
     * @author rong yuan
     * @date 2019-7-24 11:19:40
     */
    @RequestMapping(value = "/phone/rewardcashout/addOrUpdate", method = RequestMethod.POST)
    public ReturnResult addOrUpdate(String token, RewardCashOutVo rewardCashOutVo) {
        RewardStaff rewardStaff = acceptToken(acceptToken(token));
        rewardCashOutVo.setStaffId(rewardStaff.getId());
        rewardCashOutVo.setStaffName(rewardStaff.getName());
        rewardCashOutVo.setStaffJobNum(rewardStaff.getJobNum());
        return rewardCashOutService.addOrUpdate(rewardCashOutVo, null);
    }

    /**
     * 跳转提现明细界面
     *
     * @param token   用户信息
     * @param applyId 应用ID
     * @return ModelAndView
     * @author rong yuan
     * @date 2019/7/9 09:08
     */
    @RequestMapping(value = "/phone/reward/myCashOutList", method = RequestMethod.GET)
    public ModelAndView myCashOutList(String token, String applyId) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("/mobile/reward/myCashOutList");
        modelAndView.addObject("token", token);
        modelAndView.addObject("applyId", applyId);
        return modelAndView;
    }

    /**
     * 分页查询我的评价
     *
     * @param token           用户信息
     * @param rewardCashOutVo 接受参数对象
     * @param page            当前页面
     * @param limit           页面数量
     * @return ReturnResult
     * @author rong yuan
     * @date 2019-7-8 15:17:40
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/phone/reward/cashOut/page", method = RequestMethod.POST)
    public ReturnResult page(String token, RewardCashOutVo rewardCashOutVo, int page, int limit) {
        WxMember wxMember = acceptToken(token);
        RewardStaff rewardStaff = acceptToken(wxMember);
        ReturnResult returnResult;
        if (rewardStaff == null) {
            returnResult = new ReturnResult(null, 0, false);
        } else {
            rewardCashOutVo.setStaffId(rewardStaff.getId());
            returnResult = rewardCashOutService.page(rewardCashOutVo, page, limit);
            if (returnResult.getData() != null) {
                List<RewardCashOutVo> rewardCashOutVoList = (List<RewardCashOutVo>) returnResult.getData();
                for (RewardCashOutVo vo : rewardCashOutVoList) {
                    vo.setHeadLogo(wxMember.getHeadLogo());
                }
            }
        }
        return returnResult;
    }

    /**
     * 跳转我的评价界面
     *
     * @param token   用户信息
     * @param applyId 应用ID
     * @return ModelAndView
     * @author rong yuan
     * @date 2019/7/9 09:08
     */
    @RequestMapping(value = "/phone/reward/myRecord", method = RequestMethod.GET)
    public ModelAndView myRecord(String token, String applyId) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("/mobile/reward/myRecord");
        modelAndView.addObject("token", token);
        modelAndView.addObject("applyId", applyId);
        return modelAndView;
    }

    /**
     * 分页查询我的评价
     *
     * @param rewardRecordVo 接受参数对象
     * @param token          用户信息
     * @param page           当前页面
     * @param limit          页面数量
     * @return ReturnResult
     * @author rong yuan
     * @date 2019-7-8 15:17:40
     */
    @RequestMapping(value = "/phone/reward/record/page", method = RequestMethod.POST)
    public ReturnResult page(RewardRecordVo rewardRecordVo, String token, int page, int limit) {
        RewardStaff rewardStaff = acceptToken(acceptToken(token));
        ReturnResult returnResult;
        if (rewardStaff == null) {
            returnResult = new ReturnResult(null, 0, false);
        } else {
            rewardRecordVo.setStaffId(rewardStaff.getId());
            rewardRecordVo.setPayStatus(RewardDictCode.REWARD_PAY_STATUS_YZF);
            returnResult = rewardRecordService.page(rewardRecordVo, page, limit);
        }
        return returnResult;
    }

    /**
     * 跳转员工认证界面
     *
     * @param token   用户信息
     * @param applyId 应用ID
     * @return ModelAndView
     * @author rong yuan
     * @date 2019/7/9 09:08
     */
    @RequestMapping(value = "/phone/reward/myVerified", method = RequestMethod.GET)
    public ModelAndView myVerified(String token, String applyId) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("/mobile/reward/myVerified");
        modelAndView.addObject("token", token);
        modelAndView.addObject("applyId", applyId);
        RewardStaff rewardStaff = acceptToken(acceptToken(token));
        if (rewardStaff == null) {
            modelAndView.addObject("verified", false);
        } else {
            modelAndView.addObject("verified", true);
        }
        return modelAndView;
    }

    /**
     * 员工认证
     *
     * @param token    用户信息
     * @param applyId  应用ID
     * @param mobile   手机号码
     * @param password 密码
     * @return ModelAndView
     * @author rong yuan
     * @date 2019/7/9 09:08
     */
    @RequestMapping(value = "/phone/reward/verified", method = RequestMethod.POST)
    public ReturnResult verified(String token, String applyId, String mobile, String password) {
        RewardStaffVo rewardStaffVo = new RewardStaffVo();
        rewardStaffVo.setApplyId(applyId);
        rewardStaffVo.setMobile(mobile);
        RewardStaff rewardStaff = rewardStaffService.selectOneByCondition(rewardStaffVo);
        if (rewardStaff == null) {
            return new ReturnResult(ErrorCode.CODE_1, "信息未录入，请与商家联系！");
        }
        if (!rewardStaff.getPassword().equals(password)) {
            return new ReturnResult(ErrorCode.CODE_1, "手机号与密码不匹配，请与商家联系！");
        }
        String msg;
        if (StringUtils.isBlank(rewardStaff.getMemberId())) {
            rewardStaff.setMemberId(acceptToken(token).getId());
            msg = "认证成功";
        } else {
            rewardStaff.setMemberId(null);
            msg = "解除认证成功";
        }
        rewardStaff.setUpdateUser(rewardStaff.getId());
        rewardStaff.setUpdateTime(new Date());
        rewardStaffService.updateByPrimaryKey(rewardStaff);
        return new ReturnResult(ErrorCode.CODE_0, msg);
    }

    /**
     * 跳转密码修改界面
     *
     * @param token   用户信息
     * @param applyId 应用ID
     * @return ModelAndView
     * @author rong yuan
     * @date 2019/7/9 09:08
     */
    @RequestMapping(value = "/phone/reward/myPassword", method = RequestMethod.GET)
    public ModelAndView myPassword(String token, String applyId) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("/mobile/reward/myPassword");
        modelAndView.addObject("token", token);
        modelAndView.addObject("applyId", applyId);
        return modelAndView;
    }

    /**
     * 修改密码
     *
     * @param token       用户信息
     * @param oldPassword 旧密码
     * @param password    新密码
     * @return ModelAndView
     * @author rong yuan
     * @date 2019/7/9 09:08
     */
    @RequestMapping(value = "/phone/reward/resetPassword", method = RequestMethod.POST)
    public ReturnResult resetPassword(String token, String oldPassword, String password) {
        RewardStaff rewardStaff = acceptToken(acceptToken(token));
        if (!rewardStaff.getPassword().equals(oldPassword)) {
            return new ReturnResult(ErrorCode.CODE_1, "账号与原密码不匹配");
        }
        rewardStaff.setPassword(password);
        rewardStaffService.updateByPrimaryKey(rewardStaff);
        return new ReturnResult(ErrorCode.CODE_0, "密码修改成功");
    }

    /**
     * 跳转我的赏金界面
     *
     * @param token   用户信息
     * @param applyId 应用ID
     * @return ModelAndView
     * @author rong yuan
     * @date 2019/7/9 09:08
     */
    @RequestMapping(value = "/phone/reward/myRewardList", method = RequestMethod.GET)
    public ModelAndView myRewardList(String token, String applyId) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("/mobile/reward/myRewardList");
        modelAndView.addObject("token", token);
        modelAndView.addObject("applyId", applyId);
        return modelAndView;
    }

    /**
     * 分页查询打赏记录
     *
     * @param token 用户信息
     * @param page  当前页面
     * @param limit 页面数量
     * @return ReturnResult
     * @author rong yuan
     * @date 2019-7-8 15:17:40
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/phone/reward/recordList/page", method = RequestMethod.POST)
    public ReturnResult page(String token, int page, int limit) {
        ReturnResult returnResult;
        RewardRecordVo rewardRecordVo = new RewardRecordVo();
        rewardRecordVo.setMemberId(acceptToken(token).getId());
        rewardRecordVo.setPayStatus(RewardDictCode.REWARD_PAY_STATUS_YZF);
        returnResult = rewardRecordService.page(rewardRecordVo, page, limit);
        if (returnResult.getData() != null) {
            WxMember wxMember;
            List<RewardRecordVo> rewardRecordVoList = (List<RewardRecordVo>) returnResult.getData();
            for (RewardRecordVo vo : rewardRecordVoList) {
                wxMember = acceptStaffId(vo.getStaffId());
                if (wxMember != null) {
                    vo.setHeadLogo(wxMember.getHeadLogo());
                }
            }
        }
        return returnResult;
    }
}